package com.stray.crawl.worker;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.protocol.HttpContext;

import com.stray.crawl.Constants;
import com.stray.crawl.Constants.HttpCtxKey;

public class HttpLogInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor {

	private final Log log = LogFactory.getLog(getClass());

	@Override
	public void process(HttpRequest req, HttpContext ctx) throws HttpException, IOException {
		Header[] headers = req.getAllHeaders();
		RequestLine reqLine = req.getRequestLine();

		Map<String, String> map = new HashMap<String, String>();
		for (Header header : headers) {
			map.put(header.getName(), header.getValue());
		}

		ctx.setAttribute(HttpCtxKey.REQUEST_SUMMARY, "(" + reqLine.getMethod() + ") " + reqLine.getUri());
		ctx.setAttribute(HttpCtxKey.REQUEST_HEADERS, map);

		if (Constants.DEBUG) {
			log.debug("* REQUEST ****************");
			log.debug(String.format("* [Summary]        URL : %s", "(" + reqLine.getMethod() + ") " + reqLine.getUri()));
			log.debug("* ************************");
			for (Header header : headers) {
				log.debug(String.format("* %20s : %s", header.getName(),header.getValue()));
			}
			log.debug("**************************");
		}
	}

	@Override
	public void process(HttpResponse resp, HttpContext ctx) throws HttpException, IOException {
		Header[] headers = resp.getAllHeaders();
		StatusLine stsLine = resp.getStatusLine();

		Map<String, String> map = new HashMap<String, String>();
		for (Header header : headers) {
			map.put(header.getName(), header.getValue());
		}

		ctx.setAttribute(HttpCtxKey.RESPONSE_SUMMARY, stsLine.getStatusCode() +  " (" + stsLine.getReasonPhrase() + ")");
		ctx.setAttribute(HttpCtxKey.RESPONSE_HEADERS, map);

		if (Constants.DEBUG) {
			log.debug("* RESPONSE ***************");
			log.debug(String.format("* [Summary]     STATUS : %s", stsLine.getStatusCode() +  " (" + stsLine.getReasonPhrase() + ")"));
			log.debug("* ************************");
			for (Header header : headers) {
				log.debug(String.format("* %20s : %s", header.getName(),header.getValue()));
			}
			log.debug("**************************");
		}
	}

}
